<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/16
 * Time: 9:44
 */
class HnhospitalOauthInterf extends UserOauthBaseInterf
{
    private $accountId;
    private $real_name;
    private $mobile;
    private $number;
    private $userType;
    private $oldId;

    public function callOauthIntf()
    {
        $type = $this->userType;
        $condition = array(
            'account_id' => $this->accountId,
            'real_name' => $this->real_name,
            'type'=>$this->userType,
            'cut_off'=>0
        );
        if($type == 1){
            //如果是职工，匹配职工号+姓名
            $condition['number'] = $this->number;
        }
        if($type == 2){
            //如果是来宾，匹配手机号+姓名
            $condition['mobile'] = $this->mobile;
        }
        $oldId = M('User')->where($condition)->getField('user_id');
        if($oldId){
            //如果已有数据，取已有的ID值
            $this->oldId = $oldId;
        }else{
            //如果没有数据，则新增，获取新增id
            $condition['mobile'] = $this->mobile;
            $userId = M('User')->add($condition);
        }
        $res = $this->doCallBack($userId);
        return $res;
    }

    public function doCallBack($userId)
    {
        $type = $this->userType;

        if($this->oldId){
            //如果已有数据，则更新已有的数据，手机号以注册时的为准
            $userId = $this->oldId;
            $res = M('User')->where(array('user_id' => $userId))->save(array('status' => 2,'mobile'=>$this->mobile,'auth_time' => time(),'update_time' => time()));
        }else{
            //如果来宾不需要审核，则更改来宾状态为已审核
            $guest_reg = M('GlobalSet')->where(array('account_id' => $this->accountId))->getField('guest_reg_enable');
            if ($guest_reg == 0 && $type == 2) {
                $res = M('User')->where(array('user_id' => $userId))->save(array('status' => 2, 'auth_time' => time()));
            }else {
                $res = M('User')->where(array('user_id' => $userId))->save(array('status' => 1));
            }
        }
        if ($res === false) {
            return array('err_code' => 1001, 'err_msg' => '认证失败!');
        }

        //更新微信用户数据
        $mWechatUser = D('Wechat/WechatUser');
        $condition = array(
            'user_id' => $userId,
            'wechat_user_id' => session('wechatUserId'),
        );
        $mWechatUser->update($condition);
        session('userId', $userId);

        return array('err_code' => 200, 'err_msg' => '认证成功!');
    }

    public function setProperties($src)
    {
        $src_vars = is_object($src) ? get_object_vars($src) : $src;
        foreach ($src_vars as $name => $value) {
            if (property_exists($this, $name)) {
                $this->$name = $value;
            }
        }
        return $this;
    }
}